package org.piggy.core.disruptor;

import com.lmax.disruptor.ExceptionHandler;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import org.piggy.common.enums.ResponseCode;
import org.piggy.core.netty.wrapper.HttpRequestWrapper;
import org.piggy.core.utils.ResponseUtil;

public class DisruptorExceptionHandler implements ExceptionHandler<DisruptorEvent> {

    @Override
    public void handleEventException(Throwable ex, long sequence, DisruptorEvent event) {
        HttpRequestWrapper httpRequestWrapper = event.getHttpRequestWrapper();
        FullHttpRequest request = httpRequestWrapper.getRequest();
        ChannelHandlerContext channelHandlerContext = httpRequestWrapper.getChannelHandlerContext();

        FullHttpResponse fullHttpResponse = ResponseUtil.getHttpResponse(ResponseCode.INTERNAL_ERROR);
        if (!HttpUtil.isKeepAlive(request)) {
            channelHandlerContext.writeAndFlush(fullHttpResponse).addListener(ChannelFutureListener.CLOSE);
        } else {
            fullHttpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
            channelHandlerContext.writeAndFlush(fullHttpResponse);
        }
    }

    @Override
    public void handleOnStartException(Throwable ex) {

    }

    @Override
    public void handleOnShutdownException(Throwable ex) {

    }
}
